package com.farmer.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.common.constants.Code;
import com.farmer.common.dto.ShopDTO;
import com.farmer.common.entity.PageResult;
import com.farmer.common.entity.ResModel;
import com.farmer.common.entity.Shop;
import com.farmer.common.entity.User;
import com.farmer.common.utils.NowDateUtils;
import com.farmer.shop.client.UserClient;
import com.farmer.shop.mapper.ShopMapper;
import com.farmer.shop.service.ShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 林邵晨
 * @since 2023-03-06
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService {

    @Resource
    private UserClient userClient;

    @Resource
    private ShopMapper shopMapper;

    /**
     * 根据id查询商品详情
     * @param shopId
     * @return
     */
    @Override
    public ShopDTO getByShopId(Integer shopId) {
        Shop shop = getById(shopId);
        ShopDTO shopDTO=null;
        if (shop!=null){
            shopDTO = getShopDTO(shop);
        }
        return shopDTO;
    }

    /**
     * 根据id删除商品
     * @param shopId
     * @return
     */
    @Override
    public ResModel deleteByShopId(Integer shopId) {
        return ResModel.success(Code.DELETE,removeById(shopId));
    }

    /**
     * 根据id集合批量删除
     * @param ids
     * @return
     */
    @Override
    public ResModel batchDelete(List<Integer> ids) {
        return ResModel.success(Code.DELETE,removeByIds(ids));
    }

    /**
     * 根据id修改商品信息
     * @param shopDTO
     * @return
     */
    @Override
    public ResModel updateShop(ShopDTO shopDTO) {
        Shop shop = BeanUtil.copyProperties(shopDTO, Shop.class);
        shop.setUpdateTime(LocalDateTime.now());
        String img="";
        for (int i = 0; i < shopDTO.getShopImg().size(); i++) {
            if (i>0){
                img+=',';
            }
            img+=shopDTO.getShopImg().get(i);
        }
        shop.setShopImg(img);
        String specification="";
        for (int i = 0; i < shopDTO.getShopSpecification().size(); i++) {
            if (i>0){
                specification+=',';
            }
            specification+=shopDTO.getShopSpecification().get(i);
        }
        shop.setShopSpecification(specification);
        return ResModel.success(Code.UPDATE,updateById(shop));
    }

    /**
     * 新增商品
     * @param shop
     * @return
     */
    @Override
    public ResModel saveShop(ShopDTO shop) {
        Shop shop1 = BeanUtil.copyProperties(shop, Shop.class);
        List<String> shopImg = shop.getShopImg();
        List<String> shopSpecification = shop.getShopSpecification();
        String img="";
        for (int i = 0; i < shopImg.size(); i++) {
            if (i>0){
                img+=',';
            }
            img+=shopImg.get(i);
        }
        shop1.setShopImg(img);
        String specification="";
        for (int i = 0; i < shopSpecification.size(); i++) {
            if (i>0){
                specification+=',';
            }
            specification+=shopSpecification.get(i);
        }
        shop1.setShopSpecification(specification);
        return ResModel.success(Code.INSERT,save(shop1));
    }

    /**
     * 分页查询商品详情
     * @param current
     * @param size
     * @param shop
     * @return
     */
    @Override
    public ResModel listByPage(Integer current, Integer size, Shop shop) {
        Page<Shop> page = new Page<>(current,size);
        LambdaQueryWrapper<Shop> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotEmpty(shop.getShopTitle()),Shop::getShopTitle,shop.getShopTitle());
        wrapper.eq(shop.getType()!=null && shop.getType()>0,Shop::getType,shop.getType());
        Page<Shop> selectPage = baseMapper.selectPage(page, wrapper);
        PageResult<ShopDTO> result = new PageResult<>();
        result.setCurrent(selectPage.getCurrent());
        result.setSize(selectPage.getSize());
        result.setTotal(selectPage.getTotal());
        ArrayList<ShopDTO> list = new ArrayList<>();
        for (Shop shops : selectPage.getRecords()) {
            ShopDTO shopDTO = getShopDTO(shops);
            list.add(shopDTO);
        }
        result.setData(list);
        return ResModel.success(Code.SUCCESS,result);
    }

    /**
     * 扣库存
     * @param shopId
     * @return
     */
    @Override
    public boolean reduceStock(Integer shopId) {
        Shop shop = getById(shopId);
        if (shop.getShopStock()<=0){
            return false;
        }
        update().setSql("shop_stock = shop_stock - 1").last("and id = "+shopId).update();
        return true;
    }

    /**
     * 根据userId查询商品列表
     * @param userId
     * @return
     */
    @Override
    public List<ShopDTO> getByShopList(Integer userId) {
        LambdaQueryWrapper<Shop> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(true,Shop::getUserId,userId);
        List<Shop> list = list(wrapper);
        ArrayList<ShopDTO> shopDTOS = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return shopDTOS;
        }
        for (Shop shop : list) {
            ShopDTO shopDTO = getShopDTO(shop);
            shopDTOS.add(shopDTO);
        }
        return shopDTOS;
    }

    /**
     * 根据userId查询下架商品
     * @param userId
     * @return
     */
    @Override
    public List<ShopDTO> getDeleteShopList(Integer userId) {
        List<Shop> list = shopMapper.getDeletedShopList(userId);
        ArrayList<ShopDTO> shopDTOS = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return shopDTOS;
        }
        for (Shop shop : list) {
            ShopDTO shopDTO = getShopDTO(shop);
            shopDTOS.add(shopDTO);
        }
        return shopDTOS;
    }

    /**
     * 解析商品信息
     * @param shop
     * @return
     */
    private ShopDTO getShopDTO(Shop shop) {
        ShopDTO shopDTO = BeanUtil.copyProperties(shop, ShopDTO.class);
        shopDTO.setUpdateTime(NowDateUtils.format(shop.getUpdateTime()));
        String shopImg = shop.getShopImg();
        if (StrUtil.isNotEmpty(shopImg)){
            shopDTO.setShopImg(Arrays.asList(shopImg.split(",")));
        }
        String shopSpecification = shop.getShopSpecification();
        if (StrUtil.isNotEmpty(shopSpecification)){
            shopDTO.setShopSpecification(Arrays.asList(shopSpecification.split(",")));
        }
        User user = userClient.getUser(shop.getUserId());
        shopDTO.setAvatar(user.getAvatar());
        shopDTO.setUsername(user.getUsername());
        return shopDTO;
    }
}
